<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- <el-button
        class="filter-item"
        type="primary"
        v-waves
        size="small"
        icon="el-icon-plus"
        @click="handleUpdate(null)"
      >添加</el-button>-->
      <el-input
        @keyup.enter.native="handleFilter"
        style="width: 200px;"
        clearable
        class="filter-item"
        size="small"
        placeholder="解绑手机号码"
        v-model="filters.mobile"
      ></el-input>
      <el-select v-model="filters.status" clearable size="small" class="filter-item">
        <el-option v-for="(item,value) in statusFilter" :key="value" :label="item" :value="value"></el-option>
      </el-select>
      <el-date-picker
        v-model="filters.startDate"
        :picker-options="datePickerOptions1"
        clearable
        class="filter-item"
        size="small"
        value-format="yyyy-MM-dd"
        type="date"
        placeholder="申请日期——开始日期"
      />
      <el-date-picker
        v-model="filters.endDate"
        :picker-options="datePickerOptions1"
        size="small"
        class="filter-item"
        value-format="yyyy-MM-dd"
        clearable
        type="date"
        placeholder="申请日期——截止日期"
      />
      <el-button
        class="filter-item"
        type="primary"
        size="small"
        v-waves
        icon="el-icon-search"
        @click="handleFilter"
      >搜索</el-button>
      <el-button
        class="filter-item"
        size="small"
        v-if="~accessable.indexOf('user_unbind:wait_check_export')"
        type="primary"
        v-waves
        icon="el-icon-document"
        @click="exportExcelFile"
      >导出</el-button>
    </div>
    <el-table
      :data="list"
      :height="tableHeight"
      @sort-change="sortChange"
      v-loading="listLoading"
      element-loading-text="给我一点时间"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column width="150" prop="mobile" align="center" label="用户注册手机号">
        <template slot-scope="scope">{{scope.row.mobile}}</template>
      </el-table-column>

      <el-table-column prop="title" align="center" label="用户联系手机号" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.contactMobile}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="imageUrl" align="center" label="图片说明" width="160">
        <template slot-scope="scope">
          <img :src="scope.row.imageUrl|absUrl" style="height:80px;" v-if="scope.row.imageUrl">
        </template>
      </el-table-column>
      <el-table-column prop="sort" align="center" label="审核状态" width="120">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statustagFilter">{{scope.row.status|statusFilter}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="videoUrl" align="center" label="音频文件" width="120">
        <template slot-scope="scope">
          <a :href="scope.row.videoUrl|absUrl" v-if="scope.row.videoUrl">音频文件</a>
        </template>
      </el-table-column>

      <el-table-column prop="startDate" align="center" label="审核时间" width="170">
        <template slot-scope="scope">
          <span>{{scope.row.checkTime | parseTime}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="startDate" align="center" label="审核人" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.checkManager}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="startDate" align="center" label="审核备注" width="170">
        <template slot-scope="scope">
          <span>{{scope.row.checkRemark}}</span>
        </template>
      </el-table-column>

      <el-table-column prop="endDate" align="center" label="解绑微信openid" width="170">
        <template slot-scope="scope">
          <span>{{scope.row.openid}}</span>
        </template>
      </el-table-column>

      <el-table-column prop="endDate" align="center" label="会员号" width="140">
        <template slot-scope="scope">
          <span>{{scope.row.virtualcard}}</span>
        </template>
      </el-table-column>

      <el-table-column prop="endDate" align="center" label="注册时间" width="170">
        <template slot-scope="scope">
          <span>{{scope.row.registerTime | parseTime}}</span>
        </template>
      </el-table-column>

      <el-table-column prop="endDate" align="center" label="解绑原因" width="170">
        <template slot-scope="scope">
          <span>{{scope.row.reason}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="endDate" align="center" label="备注" width="170">
        <template slot-scope="scope">
          <span>{{scope.row.remark}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" align="center" label="操作时间" width="170">
        <template slot-scope="scope">
          <span>{{scope.row.createTime | parseTime}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
        width="200"
        fixed="right"
        class-name="small-padding"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            v-if="scope.row.status==0 && ~accessable.indexOf('user_unbind:wait_check_check')"
            size="mini"
            @click="handlerResolve(scope.row)"
          >审核通过</el-button>
          <el-button
            size="mini"
            v-if="scope.row.status==0 && ~accessable.indexOf('user_unbind:wait_check_check')"
            type="danger"
            @click="handlerReject(scope.row)"
          >审核驳回</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="filters.page"
        :page-sizes="[10,20,30,50]"
        :page-size="filters.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-dialog :title="isEditing?'修改':'添加'" :visible.sync="dialogFormVisible" width="1200px">
      <el-form
        class="dialog-form"
        :rules="rules"
        ref="dataForm"
        :model="temp"
        label-position="left"
        label-width="170px"
      >
        <el-form-item label="解绑用户" prop="userId">
          {{temp.selectedUserNames}}
          <el-button type="primary" @click="showUserSelectDialog" size="mini">选择</el-button>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户注册手机号" prop="mobile">
              <el-input v-model="temp.mobile" maxlength="11" placeholder="用户注册手机号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户联系手机号" prop="contactMobile">
              <el-input v-model="temp.contactMobile" maxlength="11" placeholder="用户联系手机号"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="注册时间" prop="registerTime">
              <el-date-picker
                v-model="temp.registerTime"
                :picker-options="datePickerOptions1"
                clearable
                class="filter-item"
                size="small"
                value-format="yyyy-MM-dd"
                type="datetime"
                placeholder="注册时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会员号" prop="virtualcard">
              <el-input v-model="temp.virtualcard" maxlength="100" placeholder="会员号"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="解绑微信openid" prop="openid">
          <el-input
            v-model="temp.openid"
            type="textarea"
            :rows="4"
            placeholder="解绑微信openid,多个openid以逗号分隔"
          />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="解绑原因" prop="reason">
              <el-input
                v-model="temp.reason"
                type="textarea"
                :rows="4"
                maxlength="300"
                placeholder="解绑原因"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="temp.remark"
                type="textarea"
                :rows="4"
                maxlength="255"
                placeholder="备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="解绑录音地址" prop="videoUrl">
          <el-input v-model="temp.videoUrl" :rows="4" maxlength="300" placeholder="解绑录音地址"/>
        </el-form-item>
        <el-form-item label="图片说明" prop="imageUrl">
          <xd-upload v-model="temp.imageUrl"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="submiting" @click="submitFormAction">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="查找用户" :visible.sync="userSelectDialogShowed" width="1000px">
      <div class="filter-container">
        <el-input
          @keyup.enter.native="handleUserFilter"
          style="width: 200px;"
          clearable
          class="filter-item"
          size="small"
          placeholder="手机号码"
          v-model="filtersForUser.mobile"
        ></el-input>

        <el-button
          class="filter-item"
          type="primary"
          size="small"
          v-waves
          icon="el-icon-search"
          @click="handleUserFilter"
        >搜索</el-button>
      </div>
      <el-table
        @selection-change="handleUserSelectionChange"
        :data="userList"
        v-loading="userListLoading"
        element-loading-text="给我一点时间"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column width="150" prop="username" align="center" label="用户名"></el-table-column>
        <el-table-column width="150" prop="telephone" align="center" label="手机号"></el-table-column>
        <el-table-column width="150" prop="virtualcard" align="center" label="会员卡号"></el-table-column>
        <el-table-column width="150" prop="points" align="center" label="积分"></el-table-column>
        <el-table-column min-width="200" prop="openid" align="center" label="openid"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userSelectDialogShowed = false">取消</el-button>
        <el-button type="primary" @click="sureSelectUserAction">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import xdUploadVue from '@/components/xdUpload.vue';
import { parseTime } from '../../filters';
let statusFilter = { 0: '待审核', 5: '审核通过', 10: '审核驳回' }
let limitLabelFlagItems = ['否', '是']
let statustagFilter = { 0: 'primary', 5: 'success', 10: 'danger' }
let discountOptions = [
  {
    value: 1,
    label: '打折'
  },
  {
    value: 2,
    label: '统一价'
  }
]
export default {
  components: {
    'xd-upload': xdUploadVue
  },
  created () {
    this.loadData()
    this.tableHeight = window.innerHeight - 300
  },
  filters: {
    statusFilter (status) {
      return statusFilter[parseInt(status)]
    },
    limitLabelFlagFilter (status) {
      return ['否', '是'][status || 0]
    },
    statustagFilter (status) {
      return statustagFilter[parseInt(status)]
    },
    discountTypeFilter (v) {
      let rt
      discountOptions.forEach(el => {
        if (el.value == v) {
          rt = el.label
        }
      })
      return rt
    },
    background (color) {
      return 'background:' + color
    }
  },
  methods: {
    handleUpdate (row) {
      if (!row) {
        Object.keys(this.temp).forEach(key => {
          this.temp[key] = '';
        })
        this.isEditing = false
      } else {
        Object.keys(this.temp).forEach(key => {
          this.temp[key] = row[key] || '';
        })
        this.isEditing = true
      }
      this.dialogFormVisible = true
    },
    handleSizeChange (size) {
      this.filters.limit = size
      this.loadData()
    },
    handleCurrentChange (page) {
      this.filters.page = page
      this.loadData()
    },
    history () {
      this.filters.history = 1
      this.handleFilter()
    },
    now () {
      this.filters.history = 0
      this.handleFilter()
    },
    loadData () {
      this.listLoading = true
      this.$post('/admin/user_unbind/unbind/list', this.filters)
        .then(data => {
          this.listLoading = false
          this.list = data.rows
          this.total = data.total
        })
        .catch(_ => {
          this.listLoading = false
        })
    },
    isOutofDate (date) {
      return date < this.getNow()
    },
    handleFilter () {
      this.filters.page = 1
      this.loadData()
    },
    handlerResolve (row) {
      this.$confirm('确认审核通过吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$post('/admin/user_unbind/unbind/check', {
          id: row.id,
          checkStatus: 1
        }).then(data => {
          this.$$notify()
          this.loadData()
        })
      })
    },
    handlerReject (row) {
      this.$prompt('确定审核驳回吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(({ value }) => {
          this.$post('/admin/user_unbind/unbind/check', {
            id: row.id,
            checkStatus: 0,
            checkRemark: value
          }).then(data => {
            this.$$notify()
            this.loadData()
          })
        })
        .catch(() => {})
    },
    sureSelectUserAction () {
      if (!this.selectedUsers || !this.selectedUsers.length) {
        this.$warning('请选择至少一个用户')
        return;
      }
      this.userSelectDialogShowed = false
      this.temp.selectedUserNames = this.selectedUsers
        .map(el => el.virtualcard)
        .join(',')
      const user = this.selectedUsers[0]
      this.temp.mobile = user.mobile
      this.temp.registerTime = parseTime(user.createTime)
      this.temp.virtualcard = user.virtualcard
      this.temp.openid = this.selectedUsers.map(el => el.openid).join(',')
      this.temp.userId = this.selectedUsers.map(el => el.id)
    },
    handleUserFilter () {
      this.userListLoading = true
      this.$post('/admin/user_unbind/user_list', this.filtersForUser)
        .then(data => {
          this.userListLoading = false
          this.userList = data
        })
        .catch(_ => {
          this.userListLoading = false
        })
    },
    showUserSelectDialog () {
      this.userSelectDialogShowed = true
    },
    manageGoods (id) {
      this.$router.push('/goods/goods_theme/manage?id=' + id)
    },
    exportExcelFile () {
      this.$post('/admin/user_unbind/exportExcel', {
        title: '解绑申请记录',
        ...this.filters,
        fields: JSON.stringify([
          {
            field: 'mobile',
            title: '用户注册手机号'
          },
          {
            field: 'contactMobile',
            title: '用户联系手机号'
          },

          {
            field: 'status',
            title: '审核状态',
            valueMap: statusFilter
          },

          {
            field: 'checkTime',
            title: '审核时间'
          },

          {
            field: 'checkManager',
            title: '审核人'
          },

          {
            field: 'checkRemark',
            title: '审核备注'
          },

          {
            field: 'openid',
            title: '解绑微信openid'
          },
          {
            field: 'virtualcard',
            title: '会员号'
          },
          {
            field: 'registerTime',
            title: '注册时间'
          },
          {
            field: 'reason',
            title: '解绑原因'
          },
          {
            field: 'remark',
            title: '备注'
          },
          {
            field: 'createTime',
            title: '申请时间'
          }
        ])
      }).then(info => {
        this.openWin(info)
      })
    },
    handleUserSelectionChange (users) {
      this.selectedUsers = users
    },
    submitFormAction () {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.submiting = true
          let func = null

          let map = {}
          let idx = 0
          this.temp.userId.forEach(el => {
            map[`userId[${idx}]`] = el
            idx++
          })
          Object.assign(map, this.temp)
          delete map.userId
          if (this.isEditing) {
            func = this.$post('/admin/user_unbind/unbind/apply', map)
          } else {
            func = this.$post('/admin/user_unbind/unbind/apply', map)
          }
          func
            .then(() => {
              this.submiting = false
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
              this.loadData()
            })
            .catch(info => {
              this.submiting = false
              // this.$message({
              //   type: "warning",
              //   message: info || "更新失败!"
              // });
            })
        }
      })
    }
  },

  data () {
    return {
      isManage: false,
      discountOptions,
      userSelectDialogShowed: false,
      dialogFormVisible: false,
      labelList: [],
      userList: [],
      userListLoading: false,
      filtersForUser: {
        mobile: ''
      },
      datePickerOptions1: {
        shortcuts: [
          {
            text: '今天',
            onClick (picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一周前',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      total: 0,
      temp: {
        mobile: '',
        contactMobile: '',
        openid: '',
        virtualcard: '',
        registerTime: '',
        reason: '',
        remark: '',
        videoUrl: '',
        imageUrl: '',
        userId: ''
      },
      limitLabelFlagItems,
      statusFilter,
      pickerOptions1: {
        //   disabledDate(time) {
        //     return time.getTime() > Date.now();
        //   },
        shortcuts: [
          {
            text: '今天',
            onClick (picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一周前',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      rules: {
        mobile: [
          {
            required: true,
            message: '用户注册手机号不能为空',
            trigger: 'change'
          }
        ],
        contactMobile: [
          {
            required: true,
            message: '用户联系手机号不能为空',
            trigger: 'change'
          }
        ],
        registerTime: [
          {
            required: true,
            message: '注册时间不能为空',
            trigger: 'change'
          }
        ],
        virtualcard: [
          {
            required: true,
            message: '会员号不能为空',
            trigger: 'change'
          }
        ],
        openid: [
          {
            required: true,
            message: '解绑微信openid不能为空',
            trigger: 'change'
          }
        ],
        reason: [
          {
            required: true,
            message: '解绑原因不能为空',
            trigger: 'change'
          }
        ],
        videoUrl: [
          {
            required: true,
            message: '请上传录音文件',
            trigger: 'change'
          }
        ],
        imageUrl: [
          {
            required: true,
            message: '请上传图片',
            trigger: 'change'
          }
        ],
        userId: [
          {
            required: true,
            message: '请选择至少一个解绑会员',
            trigger: 'change',
            type: 'array'
          }
        ]
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.item {
  line-height: 2.5em;
}

.box-card {
  margin-bottom: 20px;
  position: relative;
  z-index: 2;
}

.box-card-bg {
  position: absolute;
  background-position: center center;
  background-size: contain;
  background-repeat: no-repeat;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  display: block;
  opacity: 0.05;
  z-index: 0;
}
.box-card-header {
  position: relative;
  z-index: 2;
}
.box-card .item {
  position: relative;
  z-index: 2;
}
.box-card .bottom {
  position: relative;
  z-index: 2;
}
.history {
  margin-bottom: 10px;
}
</style>
